import axios from 'axios'
import { Toast } from 'mint-ui'
import store from '../store'
import { getCookie, setCookie, removeAllCookie } from '@/utils/auth'
import { refreshToken } from '@/api/api'
import router from '../router';

// 创建axios实例
const service = axios.create({
  baseURL: process.env.API_ROOT, // api 的 base_url
  timeout: 5000, // 请求超时时间
  // headers: { "Content-Type": "multipart/form-data" }
})

// request拦截器
service.interceptors.request.use(
  config => {
    //store.dispatch("setLoadingState", true) //开启loading
    if (store.getters.token) {
      config.headers['Access-Token'] = getCookie('token') // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    //store.dispatch("setLoadingState", false)  //关闭loading
    /**
     * code为非200是抛错 可结合自己业务进行修改
     */
    const res = response.data

    switch (res.code) {
      case 200:
        return response.data
        break;
      case 4001: //token不能为空
        Toast('登录信息已失效');
        removeAllCookie();
        router.push({ path: '/login' })
        return response.data
        break;
      case 4002: //token不合法
        Toast('登录信息已失效');
        removeAllCookie();
        router.push({ path: '/login' })
        return response.data
        break;
      case 4003: //token不存在  多点登陆
        Toast('登录信息已失效');
        removeAllCookie();
        router.push({ path: '/login' })
        return response.data
        break;
      case 4004: //4004:token已过期 刷新token
        refreshToken().then(res => {
          if( res.code == 200 ){
            //重置tooken
            setCookie('token','dlb '+ res.data.token,36500)
            store.dispatch("resetToken", "dlb " + res.data.token);
            //重新请求当前页面
            router.go(0)
          }
        })
        break;
      case 600003:   // 断网
        Toast('请稍后刷新尝试');
        router.push({ path: '/' })
        break;
      case 0:    // 错误
        if(res.msg != ''){
          Toast({
            message: res.msg,
            iconClass: 'icon iconfont icon-dingdanzhuangtaishibai'
          })
          return Promise.reject('error')
        }
        break;
      default:
        Toast(res.msg);
        return response.data
    }
  },
  error => {
    //store.dispatch("setLoadingState", false)  //关闭loading
    Toast({
      message: "网络错误",
      duration: 1000,
      iconClass: 'icon iconfont icon-dingdanzhuangtaishibai'
    })
    return Promise.reject(error)
  }
)

export default service
